/**
 * @Author: Bob
 *
 * @Date: 2017-11-14
 *
 * @Description: Linux下根据网卡名称获取网络连接状态或者网线是否插入
 *               参考文献：http://www.cnblogs.com/DawaTech/articles/5525873.html
 *						   http://blog.csdn.net/u010779194/article/details/10564227
 *
 */

#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <string.h>


int network_status_detect(char *net_name)
{
	int socket_fd = -1;
	int ret = -1;
    struct ifreq ifr;
	memset(&ifr, 0, sizeof(ifr));
	
	do
	{
		socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
		if (socket_fd < 0)
		{
			printf("[%s:%d][Bob] socket create failed!\n", __FILE__, __LINE__);
			break;
		}
		
		strcpy(ifr.ifr_name, net_name);
		if (ioctl(socket_fd, SIOCGIFFLAGS, &ifr) < 0)
		{
			printf("[%s:%d][Bob] ioctl error! Maybe ethernet inferface %s is not valid!\n", __FILE__, __LINE__, ifr.ifr_name);
			break;
		}

		if (ifr.ifr_flags & IFF_RUNNING)
		{
			printf("[%s:%d][Bob] %s is running\n", __FILE__, __LINE__, ifr.ifr_name);
			ret = 0;
			break;
		}
	}while(0);
	
	if (socket_fd >= 0)
	{
		close(socket_fd);
	}
	
	return ret;
}


int check_network_status(char *net_name)
{
	struct ethtool_value
	{
		//__uint32_t cmd;
		//__uint32_t data;
		unsigned int cmd;
		unsigned int data;
	};
	
	struct ethtool_value edata;
    int socket_fd = -1, ret = 0;
	struct ifreq ifr;
    memset(&ifr, 0, sizeof(ifr));
    
	do
	{
		socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
		if (socket_fd < 0)
		{
			//printf("[%s:%d][Bob] socket create failed!\n", __FILE__, __LINE__);
			break;
		}
		
		strcpy(ifr.ifr_name, net_name);
		edata.cmd = 0x0000000A;
		ifr.ifr_data = (caddr_t)&edata;
		if (ioctl(socket_fd, 0x8946, &ifr) == 0)
		{
			ret = (edata.data == 1 ? 1: 0);
			//printf("[%s:%d][Bob] %s is running,Link detected:%s\n", __FILE__, __LINE__, ifr.ifr_name, edata.data ? "yes":"no");
		}
	}while(0);
	
	if (socket_fd >= 0)
	{
		close(socket_fd);
	}
	
    return ret;
}


int main(int argc, char argv[])
{
	while(1)
	{
		//network_status_detect("ens33");
		//check_network_status("ens33");
		//network_status_detect("eth0");
		if (check_network_status("eth0"))
		{
			printf("[%s:%d][Bob] network is running,Link detected\n", __FILE__, __LINE__);
		}
		else
		{
			printf("[%s:%d][Bob] network is not running\n", __FILE__, __LINE__);
		}
		sleep(1);
	}
	
	return 0;
}